<?php
date_default_timezone_set('Asia/Shanghai');
use Workerman\Worker;
use Workerman\Timer;
require_once __DIR__ . '/Autoloader.php';
require_once __DIR__ . '/vendor/autoload.php';
$worker = new Worker('tcp://0.0.0.0:'.port());
Worker::$stdoutFile = 'chart.log';
$worker->count = 1;
// 进程启动后定时推送数据给客户端
$worker->onWorkerStart = function($worker){
    Timer::add(0.01, function()use($worker){
        foreach($worker->connections as $connection) {
            $connection->send(hex2bin('56010057'));
        }
    });

};
$worker->onConnect = function($data){
    echo "conn finsh\n";
};
$worker->onMessage = function($con,$data) use ($worker){
    $data = bin2hex($data);
    post_data($data);
    echo $data;
};
$worker->onClose = function($data){
    echo "close conn\n";
};
$worker->onError = function($data){
    echo "err\n";
};
function port(){
    $port = 778;//端口号
    return $port;
}
function post_data($data){
    $curl = curl_init();
    $url = "http://192.168.0.66:66/index.php/home/chart/post_hongwai";
    //设置post数据
    $post_data  =  array (
        "data"  =>  $data,
        "port"  =>  port(),
    ) ;
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    if(curl_errno($curl)) {
        return 'Errno'.curl_errno($curl);
    }
    curl_close($curl);

}
Worker::runAll();

